<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px" style="padding-right: 12px;">
      <el-row>
        <el-col :span="8" style="padding-left: 12px; padding-right: 12px;">
          <el-form-item label="组织" prop="name" style="width: 100%;">
            <el-tree-select
                v-model="queryParams.deptId"
                :data="deptOptions"
                :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
                value-key="deptId"
                placeholder="选择组织"
                check-strictly
              />
          </el-form-item>
        </el-col>
        <el-col :span="8" style="padding-left: 12px; padding-right: 12px;">
          <el-form-item label="组织类别" prop="type" style="width: 100%;">
            <el-select v-model="queryParams.type" placeholder="请选择组织类别" clearable>
              <el-option
                v-for="dict in pb_org_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8" style="margin: 15px 0px;">
      <el-col :span="1.5">
        <el-button type="danger" @click="viewOrgTree">组织架构</el-button>
      </el-col>
      <el-col :span="1.5">
          <el-button
              icon="Upload"
              @click="handleImport"
              v-hasPermi="['partybuilding:Org:import']"
          >导入</el-button>
        </el-col>

        <el-col :span="1.5">
          <el-button
            icon="Download"
            @click="handleExport"
            v-hasPermi="['partybuilding:Org:export']"
          >导出</el-button>
        </el-col>

        <el-col :span="1.5">
            <el-button
               type="info"
               plain
               icon="Sort"
               @click="toggleExpandAll"
            >展开/折叠</el-button>
         </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" @handleQuery="handleQuery" @resetQuery="resetQuery"></right-toolbar>
    </el-row>

    
    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="orgList"
      row-key="deptId"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column prop="deptName" label="党组织名称" align="left" width="410"></el-table-column>
      <el-table-column prop="orderNum" label="党组织概况" align="left" width="540">
        <template #default="scope">
        党员：{{ scope.row.statMember }}   班子成员：{{ scope.row.statTeamPerson }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" class-name="small-padding fixed-width">
        <template #default="scope">
            <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['partybuilding:Org:add']">新增下级</el-button>
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['partybuilding:Org:edit']">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>


    <!-- 添加或修改组织信息对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" height="600px" append-to-body style="margin-top: 109px!important;">
      <div class="dialog-top-line"></div>
      <el-form ref="OrgRef" :model="form" :rules="rules" label-width="109px">
        <div style="font-size: 18px;font-family: PingFangSC-Regular;color: #333;margin: 19px;">党组织信息</div>
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级组织" prop="parentId">
              <el-tree-select
                v-model="form.parentId"
                :data="deptOptions"
                :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
                value-key="deptId"
                placeholder="选择上级组织"
                check-strictly
                @node-click="handleClickParentOrg"
                :disabled="!isEdit"
              />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="党组织全称" prop="deptName">
              <el-input v-model="form.deptName" placeholder="请输入党组织全称" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="党组织简称" prop="nickName">
              <el-input v-model="form.nickName" placeholder="请输入党组织简称" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="组织类别" prop="type">
              <el-select v-model="form.type" placeholder="请选择组织类别">
                  <el-option
                      v-for="dict in pb_org_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                  ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="成立时间" prop="foundTime">
              <el-date-picker clearable
                v-model="form.foundTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择成立时间">
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="位置" prop="location">
              <el-input v-model="form.location" readonly placeholder="请选择地图位置">
                <template #append>
                  <el-button icon="AddLocation" style="color: red;font-size: 20px;padding-top:5px;" @click="handleMapClick"/>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div style="margin: 25px 19px;"></div>
      <div class="dialog-bottom-line"></div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
        <el-upload
          ref="uploadRef"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url + '?updateSupport=' + upload.updateSupport"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <template #tip>
              <div class="el-upload__tip text-center">
                <span>仅允许导入xls、xlsx格式文件。</span>
                <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
              </div>
          </template>
        </el-upload>
        <template #footer>
          <div class="dialog-footer">
              <el-button type="primary" @click="submitFileForm">确 定</el-button>
              <el-button @click="upload.open = false">取 消</el-button>
          </div>
        </template>
    </el-dialog>

    <!-- 查看组织架构对话框 -->
    <org-tree ref="orgTreeRef"/>

    <!-- 选择经纬度 -->
    <select-map-position ref="mapPositionRef" :parentMethod="mapPositionMethod"></select-map-position>
  </div>
</template>

<script setup name="Org">
import { getToken } from "@/utils/auth";
import { statList, listOrg, getDeptVo, delOrg, addOrg, updateOrg } from "@/api/partybuilding/Org";
import OrgTree  from "./OrgTree.vue";
import selectMapPosition from './components/selectMapPosition.vue';
const { proxy } = getCurrentInstance();
const { pb_org_type } = proxy.useDict("pb_org_type");
const orgList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const title = ref("");
const isExpandAll = ref(true);
const refreshTable = ref(true);
const deptOptions = ref(undefined);
const isEdit = ref(false);
const data = reactive({
  form: {},
  queryParams: {
    type: null,
    deptId: null
  },
  rules: {
    deptName: [
      { required: true, message: "党组织全称不能为空", trigger: ["change", "blur"] }
    ],
    type: [
      { required: true, message: "请选择组织类别", trigger: ["change", "blur"] }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/*** 组织导入参数 */
const upload = reactive({
  // 是否显示弹出层（组织导入）
  open: false,
  // 弹出层标题（组织导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/partybuilding/Org/importData"
});
/** 导入按钮操作 */
function handleImport() {
  upload.title = "组织导入";
  upload.open = true;
};

/** 下载模板操作 */
function importTemplate() {
  proxy.download("/partybuilding/Org/importTemplate", {
  }, `member_template_${new Date().getTime()}.xlsx`);
};

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
};

// 查看组织架构
function viewOrgTree() {
  proxy.$refs["orgTreeRef"].showOrgTree();
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('/partybuilding/Org/export', {
    ...queryParams.value
  }, `Org_${new Date().getTime()}.xlsx`)
}

/** 查询组织信息列表 */
function getList() {
  loading.value = true;
  statList(queryParams.value).then(response => {
    orgList.value = proxy.handleTree(response.data, "deptId");
    loading.value = false;
  });
}

/** 查询部门下拉树结构 */
function getTreeselect() {
  listOrg().then(response => {
    deptOptions.value = proxy.handleTree(response.rows, "deptId");
  });
};

//选择经纬度回调函数
function mapPositionMethod(lngValue, latValue, centerLngValue, centerLatValue, zoomValue) {
  form.value.location = `${lngValue},${latValue},${centerLngValue},${centerLatValue},${zoomValue}`;
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    nickName: null,
    typeId: null,
    foundTime: null,
    type: null,
    location: null,
    deptId: null,
    unitName: null,
    unitType: null
  };
  proxy.resetForm("OrgRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.value.type = null;
  queryParams.value.deptId = null;
  proxy.resetForm("queryRef");
  handleQuery();
}

// 获取上级组织名称
function handleClickParentOrg(data) {
  form.value.parentDeptName = data.label;
}

/** 新增按钮操作 */
function handleAdd(row) {
  reset();
  if (row != null) {
    form.value.parentId = row.deptId;
    form.value.parentDeptName = row.deptName; 
  }
  isEdit.value = false;
  open.value = true;
  title.value = "添加组织信息";
}

/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  getTreeselect();
  getDeptVo(row.deptId).then(response => {
    form.value = response.data;
    form.value.type = form.value.type!=null?form.value.type+'':'';
    form.value.unitType = form.value.unitType!=null?form.value.unitType+'':'';
    let dept = {};
    dept.parentId = response.data.parentId;
    dept.deptName = response.data.parentName;
    form.value.dept = dept;
    form.value.deptId = response.data.deptId;
    isEdit.value = true;
    open.value = true;
    title.value = "修改组织信息";
  });
}

/** 提交按钮 */
function submitForm() {
  let dept = {};
  dept.parentId = form.value.parentId;
  dept.deptName = form.value.deptName;
  form.value.dept = dept;
  console.log(form.value);
  proxy.$refs["OrgRef"].validate(valid => {
    if (valid) {
      if (form.value.deptId != null) {
        updateOrg(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addOrg(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

// 弹出地图位置
function handleMapClick() {
  let tempPoint = {title: '', lng: 111.207791, lat: 34.776053, centerLng: 111.207791, centerLat: 34.776053, zoom: 17};
  if (form.value.location !== null && form.value.location.length>0){
    let locationArray = form.value.location.split(",");
    if (locationArray!=null && locationArray.length >0) {
      tempPoint = {title: form.value.deptName, lng: locationArray[0], lat: locationArray[1], centerLng: locationArray[2], centerLat: locationArray[3], zoom: locationArray[4]};
    }
  }
  proxy.$refs["mapPositionRef"].showPosition(tempPoint);
}

getTreeselect();
getList();
</script>
<style>
.bm-view {
    width: 100%;
    height: 94%; /* 必须设置宽高 */
}
</style>
<style lang="scss" scoped>
  .dialog-top-line {
    width: 100%;
    height: 1px;
    background-color: #ccc;
    position: absolute;
    left: 0px;
    top: 50px;
  }
  .dialog-bottom-line {
    width: 100%;
    height: 1px;
    background-color: #ccc;
    position: absolute;
    left: 0px;
    bottom: 65px;
  }
  .framework {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    overflow-x: auto;
  }
</style>